<template>
  <div class="main">
    <a-form-model class="user-layout-login" @keyup.enter.native="handleSubmit">
      <div class="hello">欢迎登录</div>
        <login-account ref="alogin" @validateFail="validateFail" @success="requestSuccess" @fail="requestFailed"></login-account>
      <a-form-model-item>
        <a-checkbox @change="handleRememberMeChange" default-checked>记住登录状态</a-checkbox>
      </a-form-model-item>
      <a-form-item style="margin-top:24px">
        <a-button size="large" type="primary" htmlType="submit" class="login-button" :loading="loginBtn" @click.stop.prevent="handleSubmit" :disabled="loginBtn">登录
        </a-button>
      </a-form-item>
    </a-form-model>
    <login-select-tenant ref="loginSelect" @success="loginSelectOk" @fail="requestFailed"></login-select-tenant>
  </div>
</template>

<script>
import Vue from 'vue'
import { welcome } from '@/utils/util'
import { ACCESS_TOKEN, ENCRYPTED_STRING, USER_NAME, USER_INFO, UI_CACHE_DB_DICT_DATA, INTERFACE_PREFIX } from '@/store/mutation-types'
import LoginSelectTenant from './LoginSelectTenant'
import { getEncryptedString } from '@/utils/encryption/aesEncrypt'
import { timeFix } from '@/utils/util'
import LoginAccount from './LoginAccount'
import { apiBaseUrl } from '@/utils/request'
import { getRoute } from '@/api/login'
import axios from 'axios'
export default {
  components: {
    LoginSelectTenant,
    LoginAccount,
  },
  data() {
    return {
      customActiveKey: 'tab1',
      rememberMe: true,
      loginBtn: false,
      encryptedString: {
        key: '',
        iv: '',
      },
    }
  },
  created() {
    Vue.ls.remove(ACCESS_TOKEN)
    this.getRouterData()
    this.rememberMe = true
  },
  methods: {
    handleTabClick(key) {
      this.customActiveKey = key
    },
    handleRememberMeChange(e) {
      this.rememberMe = e.target.checked
    },
    /**跳转到登录页面的参数-账号获取*/
    getRouterData() {
      this.$nextTick(() => {
        let temp = this.$route.params.username || this.$route.query.username || ''
        if (temp) {
          this.$refs.alogin.acceptUsername(temp)
        }
      })
    },

    //登录
    handleSubmit() {
      this.loginBtn = true
      this.$refs.alogin.handleLogin(this.rememberMe)
    },
    // 校验失败
    validateFail() {
      this.loginBtn = false
    },
    // 登录后台成功
    requestSuccess(params) {
      // this.saveStore(rentList)
      // return
      // if (rentList.length <= 1) {
      //   this.saveStore(rentList)
      // } else {
      //   this.$refs.loginSelect.show(rentList)
      // }
        this.$refs.loginSelect.show(params)
    },
    saveStore(result) {
      const userInfo = result.userInfo
      userInfo.rememberMe = this.rememberMe ? 'true' : 'false'
      sessionStorage.setItem('rememberMe',this.rememberMe)
      Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
      Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
      Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
      this.$store.commit('SET_TOKEN', result.token)
      this.$store.commit('SET_INFO', userInfo)
      this.$store.commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
      this.$store.commit('SET_AVATAR', userInfo.avatar)
      // this.secondRequest(result.token)
      Vue.ls.set(USER_INFO, result.userInfo, 7 * 24 * 60 * 60 * 1000)
      Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
      // 获取所有应用的接口前缀并存储
      getRoute(result.token, `/jksaas-mgt/mgt/newSys/permission/getRoute`).then(res => {
        Vue.ls.set(INTERFACE_PREFIX, res.data.result, 7 * 24 * 60 * 60 * 1000)
        this.$store.commit('SET_INTERFACE_PREFIX', res.data.result)
      })
      this.loginSuccess()
    },
    secondRequest(token) {
      axios({
        method: 'post',
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          'X-Access-Token': token,
        },
        url: apiBaseUrl + '/jksaas-produce/produce/third/multi/Login',
        data: {
          token,
        },
      })
        .then((res) => {
          if (res.data.code == 200) {
            let result = res.data.result
            Vue.ls.set(USER_INFO, result.userInfo, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
            this.loginSuccess()
          } else {
            this.$antdMessage.warning(res.message)
          }
        })
        .catch((err) => {
          this.$emit('fail', err)
        })
    },
    //登录后台失败
    requestFailed(err) {
      let description = ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试'
      this.$notification['error']({
        message: '登录失败',
        description: description,
        duration: 4,
      })
      //账户密码登录错误后更新验证码
      this.$refs.alogin.handleChangeCheckCode()
      this.loginBtn = false
    },
    loginSelectOk(selectData) {
      this.saveStore(selectData)
    },
    //登录成功
    loginSuccess() {
      console.log('是这里登录成功跳转的吗???');
      this.$router.push({ path: '/' }).catch(() => {
        console.log('登录跳转首页出错,这个错误从哪里来的')
      })
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`,
      })
      setTimeout(() => {
        this.loginBtn = false
      }, 3000);
    },

    //获取密码加密规则
    getEncrypte() {
      var encryptedString = Vue.ls.get(ENCRYPTED_STRING)
      if (encryptedString == null) {
        getEncryptedString().then((data) => {
          this.encryptedString = data
        })
      } else {
        this.encryptedString = encryptedString
      }
    },
  },
}
</script>
<style lang="less" scoped>
.user-layout-login {
  position: absolute;
  right: 10%;
  top: 22%;
  width: 400px;
  background: #FFFFFF;
  box-shadow: 0px 9px 28px 4px rgba(0,0,0,0.03);
  border-radius: 16px;
  padding: 20px 40px 40px;
  .hello {
    text-align: center;
    font-size: 32px;
    font-family: PingFang SC;
    font-weight: bold;
    color: #101328;
    // margin-bottom: 20px;
  }
  label {
    font-size: 14px;
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    height: 44px;
    width: 100%;
    font-size: 18px;
    font-family: PingFang SC;
    font-weight: 500;
    line-height: 44px;
    color: #FFFFFF;
    background: #1890ff;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
<style>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
</style>